from fastapi import Request, HTTPException
from fastapi.responses import RedirectResponse, JSONResponse
from jose import jwt, JWTError
from auth import SECRET_KEY, ALGORITHM
from database import SessionLocal
from models import Admin

async def admin_auth_middleware(request: Request, call_next):
    """检查管理界面的认证状态"""
    # 如果是登录页面、静态资源或getData/hotspots API，直接放行
    if request.url.path == "/login" or request.url.path.startswith("/static") or request.url.path.startswith("/token") or request.url.path == "/api/getData" or request.url.path == "/api/hotspots":
        return await call_next(request)

    # 获取令牌
    token = None

    # 首先尝试从Authorization头获取令牌
    auth_header = request.headers.get("Authorization")
    if auth_header and auth_header.startswith("Bearer "):
        token = auth_header.split(" ")[1]

    # 如果Authorization头中没有令牌，尝试从cookie中获取
    if not token:
        token = request.cookies.get("access_token")
        # 如果从cookie中获取到token，去掉可能的引号
        if token and (token.startswith('"') and token.endswith('"')):
            token = token[1:-1]

    # 只有admin路径下的页面才需要认证
    if request.url.path.startswith("/admin"):
        # 如果两种方式都没有获取到令牌，重定向到登录页面
        if not token:
            return RedirectResponse(url="/login")

        # 验证令牌并获取当前用户
        try:
            # 创建数据库会话
            db = SessionLocal()

            # 解码JWT令牌
            payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
            username: str = payload.get("sub")
            if username is None:
                raise HTTPException(status_code=401, detail="无法验证凭据")

            # 查询用户
            user = db.query(Admin).filter(Admin.username == username).first()
            if user is None:
                raise HTTPException(status_code=401, detail="用户不存在")

            # 将当前用户信息添加到请求状态中，以便路由处理函数使用
            request.state.user = user

            # 关闭数据库会话
            db.close()
        except Exception as e:
            print(f"认证失败: {e}")
            return RedirectResponse(url="/login")

    # 如果是API请求且没有认证，返回401错误（排除getData和hotspots API）
    elif request.url.path.startswith("/api/") and request.url.path != "/api/getData" and request.url.path != "/api/hotspots":
        # 如果两种方式都没有获取到令牌，返回401错误
        if not token:
            return JSONResponse(
                status_code=401,
                content={"detail": "未授权访问"}
            )

        # 验证令牌并获取当前用户
        try:
            # 创建数据库会话
            db = SessionLocal()

            # 解码JWT令牌
            payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
            username: str = payload.get("sub")
            if username is None:
                raise HTTPException(status_code=401, detail="无法验证凭据")

            # 查询用户
            user = db.query(Admin).filter(Admin.username == username).first()
            if user is None:
                raise HTTPException(status_code=401, detail="用户不存在")

            # 将当前用户信息添加到请求状态中，以便路由处理函数使用
            request.state.user = user

            # 关闭数据库会话
            db.close()
        except Exception as e:
            print(f"认证失败: {e}")
            return JSONResponse(
                status_code=401,
                content={"detail": "认证失败"}
            )

    # 处理请求
    response = await call_next(request)
    return response

